package com.borya.task;

import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.borya.task.time.HashTimer;
import com.borya.util.DateUtils;

import io.netty.util.Timeout;
import io.netty.util.TimerTask;

public abstract class AbstractTaskService implements TaskService {
	private Logger log = Logger.getLogger(getClass());
	
	private final String DAILYTIME;
	
	public AbstractTaskService(String dAILYTIME) {
		super();
		DAILYTIME = dAILYTIME;
	}

	public void start1() {
		try {
			long delayTime = 0;
			long time = System.currentTimeMillis();
			String date = DateUtils.format(time, "yyyy-MM-dd ") + DAILYTIME;
			long a = DateUtils.parseDate(date, "yyyy-MM-dd HH:mm:ss");
			delayTime =(a > time) ? ( a - time):(a + TimeUnit.DAYS.toMillis(1) - time);
			HashTimer.newTimeout(task(),delayTime,TimeUnit.SECONDS);
		} catch (Exception e){
			log.error(e.getMessage(),e);
		}
	}

	private TimerTask task(){
		return new TimerTask() {
			@Override
			public void run(Timeout timeout) {
				process();
				//再此把任务加入定时器中，设置延迟周一为一天
				HashTimer.newTimeout(this,TimeUnit.DAYS.toSeconds(1),TimeUnit.SECONDS);
			}
		};
	}

}
